package main.java.com.chankudo.network;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class SimpleTcpClient {
    int port;
    
    public SimpleTcpClient(int port){
        this.port = port;
        
    }

    void waitAndSend(){
        try(Scanner scanner = new Scanner(System.in)){
            System.out.println("want to sent sever? y to continue , n to end.");
            String yStr =scanner.nextLine();
            if(!"y".equals(yStr)){
                return;
            }

            PrintWriter writer = null;
            try(Socket socket = new Socket("localhost", port)){
                while("y".equals(yStr) || "n".equals(yStr)){
                    OutputStream outputStream = socket.getOutputStream();
                    writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);
                    System.out.println("please input message:");
                    String str = scanner.nextLine();
                    writer.println(str);
                    if("n".equals(str)){
                        break;
                    }
                    System.out.println("want to sent sever? y to continue ,n to end. others input will be ignored.");
                    yStr =scanner.nextLine();
                    while(!"y".equals(yStr) && !"n".equals(yStr)){
                        System.out.println("invalid input! please input y or n.");
                        yStr =scanner.nextLine();
                    }
                }
            }catch(IOException ioe){
                ioe.printStackTrace();
            }finally{
                if(writer!=null){
                    writer.close();
                }
            }
            System.out.println("client close");
            //System.out.println("bye.");
            
        }
    }
}
